"""
求职者端API路由
提供职位搜索、简历优化、面试准备等功能
"""

from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, status
from sqlalchemy.orm import Session
from typing import List, Optional
import json
import os
import shutil
from datetime import datetime

from ..dependencies import get_db, get_current_user
from ..models import (
    # 数据库模型
    User, JobPosition, Resume, JobApplication, CandidateProfile, Company,
    # Pydantic模型
    JobSearchRequest, JobPositionResponse,
    JobMatchRequest, JobMatchResponse,
    JobApplicationCreate, JobApplicationResponse,
    ResumeUploadResponse, ResumeOptimizationRequest, ResumeOptimizationResponse,
    InterviewPrepRequest, InterviewPrepResponse,
    CandidateAnalyticsDashboard, SmartRecommendationRequest, SmartRecommendationResponse,
    CandidateProfileCreate, CandidateProfileResponse
)
from ....core.container import Container
# from ....lightrag_engine.ingestion.document_parser import DocumentParser  # 临时注释，lightrag开发中

router = APIRouter(prefix="/candidate", tags=["求职者端功能"])

@router.get("/dashboard/analytics", response_model=CandidateAnalyticsDashboard)
async def get_candidate_analytics(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
    container: Container = Depends(lambda: Container())
):
    """获取候选人分析仪表板"""
    if current_user.user_type != "candidate":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有求职者可以访问此功能"
        )
    
    candidate_profile = db.query(CandidateProfile).filter(
        CandidateProfile.user_id == current_user.id
    ).first()
    
    if not candidate_profile:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="候选人档案不存在"
        )
    
    # 使用智能体分析候选人数据
    task_config = {
        "description": "候选人个人分析仪表板",
        "candidate_data": {
            "profile": {
                "name": candidate_profile.full_name,
                "skills": candidate_profile.skills,
                "experience": candidate_profile.experience_years,
                "location": candidate_profile.location,
                "education": candidate_profile.education
            }
        },
        "task_type": "candidate_analytics"
    }
    
    try:
        orchestrator = container.orchestrator()
        result = await orchestrator.orchestrate_task(task_config)
        
        if result.get("status") == "completed":
            analytics_data = result.get("result", {})
            
            return CandidateAnalyticsDashboard(
                profile_completeness=analytics_data.get("profile_completeness", 0.0),
                skill_market_demand=analytics_data.get("skill_market_demand", {}),
                salary_insights=analytics_data.get("salary_insights", {}),
                application_success_rate=analytics_data.get("application_success_rate", 0.0),
                recommended_improvements=analytics_data.get("recommended_improvements", []),
                industry_trends=analytics_data.get("industry_trends", [])
            )
        else:
            # 返回默认数据
            return CandidateAnalyticsDashboard(
                profile_completeness=75.0,
                skill_market_demand={"Python": 0.8, "JavaScript": 0.7},
                salary_insights={"market_average": 80000, "your_range": "70000-90000"},
                application_success_rate=25.0,
                recommended_improvements=["完善项目经验", "增加技能证书"],
                industry_trends=[{"trend": "AI技能需求增长", "impact": "high"}]
            )
            
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"分析失败: {str(e)}"
        )

@router.post("/profile", response_model=CandidateProfileResponse)
async def create_or_update_profile(
    profile_data: CandidateProfileCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建或更新候选人档案"""
    if current_user.user_type != "candidate":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有求职者可以创建档案"
        )
    
    # 检查是否已有档案
    existing_profile = db.query(CandidateProfile).filter(
        CandidateProfile.user_id == current_user.id
    ).first()
    
    if existing_profile:
        # 更新现有档案
        for field, value in profile_data.dict().items():
            setattr(existing_profile, field, value)
        db.commit()
        db.refresh(existing_profile)
        return existing_profile
    else:
        # 创建新档案
        new_profile = CandidateProfile(
            user_id=current_user.id,
            **profile_data.dict()
        )
        db.add(new_profile)
        db.commit()
        db.refresh(new_profile)
        return new_profile

@router.post("/jobs/search", response_model=List[JobPositionResponse])
async def search_jobs(
    search_request: JobSearchRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """智能职位搜索"""
    if current_user.user_type != "candidate":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有求职者可以搜索职位"
        )
    
    # 构建查询
    query = db.query(JobPosition).join(Company).filter(JobPosition.is_active == True)
    
    # 应用筛选条件
    if search_request.keywords:
        query = query.filter(
            JobPosition.title.contains(search_request.keywords) |
            JobPosition.description.contains(search_request.keywords)
        )
    
    if search_request.experience_level:
        query = query.filter(JobPosition.experience_level == search_request.experience_level.value)
    
    if search_request.location:
        query = query.filter(JobPosition.location.contains(search_request.location))
    
    if search_request.employment_type:
        query = query.filter(JobPosition.employment_type == search_request.employment_type)
    
    if search_request.industry:
        query = query.filter(Company.industry == search_request.industry)
    
    # 分页
    jobs = query.offset(search_request.offset).limit(search_request.limit).all()
    
    return jobs

@router.post("/jobs/match", response_model=List[JobMatchResponse])
async def get_job_matches(
    match_request: JobMatchRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
    container: Container = Depends(lambda: Container())
):
    """获取职位匹配推荐"""
    if current_user.user_type != "candidate":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有求职者可以获取职位匹配"
        )
    
    # 获取候选人档案
    candidate_profile = db.query(CandidateProfile).filter(
        CandidateProfile.user_id == current_user.id
    ).first()
    
    if not candidate_profile:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="请先完善候选人档案"
        )
    
    # 获取要分析的职位
    if match_request.job_ids:
        jobs = db.query(JobPosition).filter(
            JobPosition.id.in_(match_request.job_ids),
            JobPosition.is_active == True
        ).limit(match_request.limit).all()
    else:
        # 获取活跃的职位进行匹配
        jobs = db.query(JobPosition).filter(
            JobPosition.is_active == True
        ).limit(match_request.limit * 2).all()  # 获取更多职位用于筛选
    
    # 使用智能体进行职位匹配分析
    task_config = {
        "description": "职位匹配分析",
        "candidate_profile": {
            "skills": candidate_profile.skills,
            "experience": candidate_profile.experience_years,
            "location": candidate_profile.location,
            "current_position": candidate_profile.current_position
        },
        "job_positions": [
            {
                "id": job.id,
                "title": job.title,
                "requirements": job.requirements,
                "experience_level": job.experience_level,
                "location": job.location,
                "description": job.description
            } for job in jobs
        ],
        "task_type": "job_matching"
    }
    
    try:
        orchestrator = container.orchestrator()
        result = await orchestrator.orchestrate_task(task_config)
        
        if result.get("status") == "completed":
            matches = result.get("result", {}).get("matches", [])
            
            # 构建响应
            job_matches = []
            for match in matches[:match_request.limit]:
                job_id = match.get("job_id")
                job = next((j for j in jobs if j.id == job_id), None)
                if job:
                    job_match = JobMatchResponse(
                        job_position=job,
                        match_score=match.get("match_score", 0.0),
                        matching_skills=match.get("matching_skills", []),
                        missing_skills=match.get("missing_skills", []),
                        recommendations=match.get("recommendations", []),
                        interview_tips=match.get("interview_tips", [])
                    )
                    job_matches.append(job_match)
            
            return job_matches
        else:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="职位匹配分析失败"
            )
            
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"职位匹配失败: {str(e)}"
        )

@router.post("/resumes/upload", response_model=ResumeUploadResponse)
async def upload_resume(
    file: UploadFile = File(...),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
    container: Container = Depends(lambda: Container())
):
    """上传并解析简历"""
    if current_user.user_type != "candidate":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有求职者可以上传简历"
        )
    
    # 获取候选人档案
    candidate_profile = db.query(CandidateProfile).filter(
        CandidateProfile.user_id == current_user.id
    ).first()
    
    if not candidate_profile:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="请先创建候选人档案"
        )
    
    # 检查文件类型
    if not file.filename.lower().endswith(('.pdf', '.doc', '.docx')):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="只支持PDF、DOC、DOCX格式文件"
        )
    
    # 保存文件
    upload_dir = "data/uploaded_resumes"
    os.makedirs(upload_dir, exist_ok=True)
    
    file_path = os.path.join(upload_dir, f"{current_user.id}_{int(datetime.now().timestamp())}_{file.filename}")
    
    with open(file_path, "wb") as buffer:
        shutil.copyfileobj(file.file, buffer)
    
    try:
        # 解析简历内容 - 临时简化实现
        # parser = DocumentParser()
        # parsed_content = parser.parse_document(file_path)
        parsed_content = {"text": "临时解析结果", "filename": file.filename}
        
        # 使用智能体进行简历分析 - 临时简化实现
        # task_config = {
        #     "description": "简历解析和初步分析",
        #     "resume_content": json.dumps(parsed_content, ensure_ascii=False),
        #     "candidate_profile": {
        #         "name": candidate_profile.full_name,
        #         "skills": candidate_profile.skills
        #     },
        #     "task_type": "resume_analysis"
        # }
        
        # orchestrator = container.orchestrator()
        # result = await orchestrator.orchestrate_task(task_config)
        
        # 临时分析结果
        analysis_result = {
            "summary": "简历分析功能开发中，暂时返回基础信息",
            "skills_detected": [],
            "experience_years": 0
        }
        score = 75.0  # 临时评分
        
        # 保存到数据库
        resume = Resume(
            candidate_id=candidate_profile.id,
            file_path=file_path,
            original_filename=file.filename,
            parsed_content=parsed_content,
            analysis_result=analysis_result,
            score=score
        )
        
        db.add(resume)
        db.commit()
        db.refresh(resume)
        
        return ResumeUploadResponse(
            id=resume.id,
            original_filename=resume.original_filename,
            file_path=resume.file_path,
            parsed_content=resume.parsed_content,
            analysis_result=resume.analysis_result,
            score=resume.score,
            created_at=resume.created_at
        )
        
    except Exception as e:
        # 如果出错，删除已上传的文件
        if os.path.exists(file_path):
            os.remove(file_path)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"简历上传失败: {str(e)}"
        )

@router.post("/resumes/{resume_id}/optimize", response_model=ResumeOptimizationResponse)
async def optimize_resume(
    resume_id: int,
    optimization_request: ResumeOptimizationRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
    container: Container = Depends(lambda: Container())
):
    """优化简历"""
    if current_user.user_type != "candidate":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有求职者可以优化简历"
        )
    
    # 获取简历
    resume = db.query(Resume).join(CandidateProfile).filter(
        Resume.id == resume_id,
        CandidateProfile.user_id == current_user.id
    ).first()
    
    if not resume:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="简历不存在"
        )
    
    # 获取目标职位信息（如果提供）
    job_requirements = ""
    if optimization_request.target_job_id:
        job = db.query(JobPosition).filter(JobPosition.id == optimization_request.target_job_id).first()
        if job:
            job_requirements = f"职位: {job.title}\n要求: {', '.join(job.requirements)}\n描述: {job.description}"
    
    # 构建优化任务
    task_config = {
        "description": "简历优化和改进建议",
        "resume_content": json.dumps(resume.parsed_content, ensure_ascii=False),
        "target_job_requirements": job_requirements,
        "target_skills": optimization_request.target_skills or [],
        "current_score": resume.score,
        "task_type": "resume_optimization"
    }
    
    try:
        orchestrator = container.orchestrator()
        result = await orchestrator.orchestrate_task(task_config)
        
        if result.get("status") == "completed":
            optimization_data = result.get("result", {})
            
            return ResumeOptimizationResponse(
                original_score=resume.score or 0.0,
                optimized_content=optimization_data.get("optimized_content", ""),
                improvements=optimization_data.get("improvements", []),
                keyword_suggestions=optimization_data.get("keyword_suggestions", []),
                structure_recommendations=optimization_data.get("structure_recommendations", []),
                ats_compatibility_score=optimization_data.get("ats_compatibility_score", 0.0)
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="简历优化失败"
            )
            
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"简历优化失败: {str(e)}"
        )

@router.post("/interview/prepare", response_model=InterviewPrepResponse)
async def prepare_for_interview(
    prep_request: InterviewPrepRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
    container: Container = Depends(lambda: Container())
):
    """准备面试"""
    if current_user.user_type != "candidate":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有求职者可以准备面试"
        )
    
    # 获取职位信息
    job = db.query(JobPosition).join(Company).filter(
        JobPosition.id == prep_request.job_position_id
    ).first()
    
    if not job:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="职位不存在"
        )
    
    # 获取候选人档案
    candidate_profile = None
    if prep_request.candidate_id:
        candidate_profile = db.query(CandidateProfile).filter(
            CandidateProfile.user_id == current_user.id
        ).first()
    
    # 构建面试准备任务
    task_config = {
        "description": "面试准备和建议生成",
        "job_position": {
            "title": job.title,
            "description": job.description,
            "requirements": job.requirements,
            "experience_level": job.experience_level,
            "company": {
                "name": job.company.name,
                "industry": job.company.industry,
                "description": job.company.description
            }
        },
        "candidate_profile": {
            "skills": candidate_profile.skills if candidate_profile else [],
            "experience": candidate_profile.experience_years if candidate_profile else 0,
            "current_position": candidate_profile.current_position if candidate_profile else ""
        } if candidate_profile else {},
        "task_type": "interview_preparation"
    }
    
    try:
        orchestrator = container.orchestrator()
        result = await orchestrator.orchestrate_task(task_config)
        
        if result.get("status") == "completed":
            prep_data = result.get("result", {})
            
            return InterviewPrepResponse(
                company_info=prep_data.get("company_info", {}),
                position_analysis=prep_data.get("position_analysis", {}),
                likely_questions=prep_data.get("likely_questions", []),
                preparation_tips=prep_data.get("preparation_tips", []),
                skill_gaps=prep_data.get("skill_gaps", []),
                improvement_suggestions=prep_data.get("improvement_suggestions", []),
                mock_interview_scenarios=prep_data.get("mock_interview_scenarios", [])
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="面试准备失败"
            )
            
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"面试准备失败: {str(e)}"
        )

@router.post("/applications", response_model=JobApplicationResponse)
async def apply_for_job(
    application_data: JobApplicationCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
    container: Container = Depends(lambda: Container())
):
    """申请职位"""
    if current_user.user_type != "candidate":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有求职者可以申请职位"
        )
    
    # 获取候选人档案
    candidate_profile = db.query(CandidateProfile).filter(
        CandidateProfile.user_id == current_user.id
    ).first()
    
    if not candidate_profile:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="请先创建候选人档案"
        )
    
    # 检查简历是否存在
    resume = db.query(Resume).filter(
        Resume.id == application_data.resume_id,
        Resume.candidate_id == candidate_profile.id
    ).first()
    
    if not resume:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="简历不存在"
        )
    
    # 检查职位是否存在
    job = db.query(JobPosition).filter(
        JobPosition.id == application_data.job_position_id,
        JobPosition.is_active == True
    ).first()
    
    if not job:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="职位不存在或已关闭"
        )
    
    # 检查是否已经申请过
    existing_application = db.query(JobApplication).filter(
        JobApplication.job_position_id == application_data.job_position_id,
        JobApplication.candidate_id == candidate_profile.id
    ).first()
    
    if existing_application:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="已经申请过该职位"
        )
    
    # 使用智能体进行匹配分析
    task_config = {
        "description": "申请匹配度分析",
        "resume_content": json.dumps(resume.parsed_content, ensure_ascii=False),
        "job_requirements": {
            "title": job.title,
            "requirements": job.requirements,
            "description": job.description,
            "experience_level": job.experience_level
        },
        "task_type": "application_analysis"
    }
    
    try:
        orchestrator = container.orchestrator()
        result = await orchestrator.orchestrate_task(task_config)
        
        match_score = 0.0
        ai_analysis = {}
        
        if result.get("status") == "completed":
            analysis_data = result.get("result", {})
            match_score = analysis_data.get("match_score", 0.0)
            ai_analysis = analysis_data
        
        # 创建申请
        application = JobApplication(
            job_position_id=application_data.job_position_id,
            resume_id=application_data.resume_id,
            candidate_id=candidate_profile.id,
            match_score=match_score,
            ai_analysis=ai_analysis
        )
        
        db.add(application)
        db.commit()
        db.refresh(application)
        
        return JobApplicationResponse(
            id=application.id,
            status=application.status,
            match_score=application.match_score,
            ai_analysis=application.ai_analysis,
            applied_at=application.applied_at,
            job_position=job,
            hr_feedback=application.hr_feedback
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"申请失败: {str(e)}"
        )

@router.get("/applications", response_model=List[JobApplicationResponse])
async def get_my_applications(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
    status: Optional[str] = None,
    limit: int = 20,
    offset: int = 0
):
    """获取我的申请列表"""
    if current_user.user_type != "candidate":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有求职者可以查看申请"
        )
    
    # 获取候选人档案
    candidate_profile = db.query(CandidateProfile).filter(
        CandidateProfile.user_id == current_user.id
    ).first()
    
    if not candidate_profile:
        return []
    
    # 构建查询
    query = db.query(JobApplication).filter(
        JobApplication.candidate_id == candidate_profile.id
    )
    
    if status:
        query = query.filter(JobApplication.status == status)
    
    applications = query.offset(offset).limit(limit).all()
    
    return applications

@router.get("/resumes", response_model=List[ResumeUploadResponse])
async def get_my_resumes(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取我的简历列表"""
    if current_user.user_type != "candidate":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有求职者可以查看简历"
        )
    
    # 获取候选人档案
    candidate_profile = db.query(CandidateProfile).filter(
        CandidateProfile.user_id == current_user.id
    ).first()
    
    if not candidate_profile:
        return []
    
    resumes = db.query(Resume).filter(
        Resume.candidate_id == candidate_profile.id
    ).all()
    
    return [
        ResumeUploadResponse(
            id=resume.id,
            original_filename=resume.original_filename,
            file_path=resume.file_path,
            parsed_content=resume.parsed_content,
            analysis_result=resume.analysis_result,
            score=resume.score,
            created_at=resume.created_at
        )
        for resume in resumes
    ]

@router.post("/recommendations", response_model=SmartRecommendationResponse)
async def get_personalized_recommendations(
    recommendation_request: SmartRecommendationRequest,
    current_user: User = Depends(get_current_user),
    container: Container = Depends(lambda: Container())
):
    """获取个性化推荐"""
    if current_user.user_type != "candidate":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有求职者可以获取推荐"
        )
    
    task_config = {
        "description": "个性化推荐生成",
        "user_id": current_user.id,
        "recommendation_type": recommendation_request.recommendation_type,
        "context": recommendation_request.context or {},
        "task_type": "personalized_recommendation"
    }
    
    try:
        orchestrator = container.orchestrator()
        result = await orchestrator.orchestrate_task(task_config)
        
        if result.get("status") == "completed":
            recommendation_data = result.get("result", {})
            
            return SmartRecommendationResponse(
                recommendations=recommendation_data.get("recommendations", []),
                reasoning=recommendation_data.get("reasoning", []),
                confidence_scores=recommendation_data.get("confidence_scores", []),
                personalization_factors=recommendation_data.get("personalization_factors", [])
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="推荐生成失败"
            )
            
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"推荐生成失败: {str(e)}"
        )